// 使用内存存储验证码(生产环境可以考虑使用Redis)
const codeStore = new Map();

/**
 * 生成6位随机验证码
 * @returns {string} 生成的验证码
 */
function generateVerifyCode() {
    return Math.floor(100000 + Math.random() * 900000).toString();
}

/**
 * 存储验证码
 * @param {string} email 邮箱地址
 * @param {string} code 验证码
 * @param {string} type 验证码类型(register/update)
 */
function saveVerifyCode(email, code, type = 'register') {
    const expireTime = Date.now() + 5 * 60 * 1000; // 5分钟有效期
    const key = `${type}_${email}`;

    codeStore.set(key, { code, expireTime });

    // 设置自动过期
    setTimeout(() => {
        if (codeStore.has(key) && codeStore.get(key).code === code) {
            codeStore.delete(key);
        }
    }, 5 * 60 * 1000);
}

/**
 * 验证验证码
 * @param {string} email 邮箱地址
 * @param {string} code 验证码
 * @param {string} type 验证码类型(register/update)
 * @returns {Object} 验证结果
 */
function verifyCode(email, code, type = 'register') {
    const key = `${type}_${email}`;

    if (!codeStore.has(key)) {
        return { valid: false, message: "验证码不存在或已过期" };
    }

    const savedData = codeStore.get(key);
    if (Date.now() > savedData.expireTime) {
        codeStore.delete(key);
        return { valid: false, message: "验证码已过期" };
    }

    if (savedData.code !== code) {
        return { valid: false, message: "验证码不正确" };
    }

    // 验证成功后删除验证码，防止重复使用
    codeStore.delete(key);
    return { valid: true };
}

module.exports = {
    generateVerifyCode,
    saveVerifyCode,
    verifyCode
}; 